<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input placeholder="Title" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-if="checkPermission(pageRoles.userPage_retrieve)" v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        Search
      </el-button>
      <el-button v-if="checkPermission(pageRoles.userPage_create)" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        Add
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" sortable="custom" align="center" width="220" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.userId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Name" sortable="custom" align="center" width="140" :class-name="getSortClass('name')">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="sex" sortable="custom" align="center" width="140" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.sex }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Dept" sortable="custom" align="center" width="140" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.deptName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Tel" sortable="custom" align="center" width="140" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.tel }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" sortable="custom" align="center" width="300">
        <template slot-scope="{row}">
          <el-button @click="handleShowDetail(row)">详情</el-button>
          <el-button v-if="checkPermission(pageRoles.userPage_delete)" @click="handleDeleteUser(row.userId)">删除</el-button>
          <el-button v-if="checkPermission(pageRoles.userPage_delete)" @click="handleModifyUser(row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 添加 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="addRules" :model="addUser" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="name" prop="name">
          <el-input v-model="addUser.name" name="name" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUser.password" />
        </el-form-item>
        <el-form-item label="确认密码" prop="password">
          <el-input v-model="addUser.confirmedPassword" />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio v-model="addUser.sex" label="男">男</el-radio>
          <el-radio v-model="addUser.sex" label="女">女</el-radio>
        </el-form-item>
        <el-form-item label="电话" prop="tel">
          <el-input v-model="addUser.tel" />
        </el-form-item>
        <el-form-item label="身份证" prop="idNumber">
          <el-input v-model="addUser.idNo" />
        </el-form-item>
        <el-form-item label="邮箱" prop="emailAddress">
          <el-input v-model="addUser.email" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="addUser.age" />
        </el-form-item>
        <el-form-item label="QQ" prop="QQ">
          <el-input v-model="addUser.qq" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input v-model="addUser.description" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="Please input" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          Cancel
        </el-button>
        <el-button type="primary" @click="addUserClick">
          添加
        </el-button>
      </div>
    </el-dialog>
    <!--  详情  -->
    <el-dialog title="详情" :visible.sync="showDetailDialog">
      <span>{{ detailUser.name }}</span>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showDetailDialog = false">
          Ok
        </el-button>
      </div>
    </el-dialog>
    <!--  修改  -->
    <el-dialog title="修改" :visible.sync="modifyUserDialogVisible">
      <el-form>
        <el-form-item label="name" prop="name">
          <el-input v-model="detailUser.name" name="name" />
        </el-form-item>
        <el-form-item label="生日" prop="timestamp">
          <el-date-picker v-model="detailUser.birth" type="datetime" placeholder="Please pick a date" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="detailUser.password" />
        </el-form-item>
        <el-form-item label="电话" prop="tel">
          <el-input v-model="detailUser.tel" />
        </el-form-item>
        <el-form-item label="身份证" prop="idNumber">
          <el-input v-model="detailUser.idNo" />
        </el-form-item>
        <el-form-item label="邮箱" prop="emailAddress">
          <el-input v-model="detailUser.email" />
        </el-form-item>
        <el-form-item label="QQ" prop="QQ">
          <el-input v-model="detailUser.qq" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input v-model="detailUser.description" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="Please input" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="modifyUserDialogVisible = false">
          Cancel
        </el-button>
        <el-button @click="handleModifySubmit">
          提交
        </el-button>
      </div>
    </el-dialog>
    <!-- 详情权限   -->
    <el-dialog title="详情权限" :visible.sync="userRolesDialogVisible">
      <el-form>
        <el-form-item label="name" prop="name">
          <el-input v-model="detailUser.name" name="name" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userRolesDialogVisible = false">
          Cancel
        </el-button>
        <el-button click="window.alert('删除')">
          删除
        </el-button>
        <el-button click="window.alert('增加')">
          增加
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { fetchPv, createArticle, updateArticle } from '@/api/article'
import { addUser, deleteUserById, fetchList, updateUser } from '@/api/user/user'
import waves from '@/directive/waves' // waves directive
// import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import permission from '@/directive/permission' // 权限判断指令
import checkPermission from '@/utils/permission' // 权限判断函数
import '@/utils/validate'
import {
  validEmailAddress, validIdNumber,
  validLegalPassword,
  validPassword,
  validPhoneNumber,
  validQQ,
  validUsername
} from '@/utils/validate'
import { fetchPageRolesByPageName } from '@/api/role'

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves, permission },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    const validateUsername = (rule, value, callback) => {
      console.log('validateUsername:' + value)
      if (!validUsername(value)) {
        callback(new Error('Please enter the correct user name'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (!validPassword(value)) {
        callback(new Error('less than 6 digits or more than 16'))
      } else if (!validLegalPassword(value)) {
        callback(new Error('只能使用中文、英文、数字包括下划线'))
      } else {
        callback()
      }
    }
    const validateConfirmedPassword = (rule, value, callback) => {
      if (this.data().addUser.password === value) {
        callback()
      } else {
        callback(new Error('两次密码不同'))
      }
    }
    const validateSex = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请选择性别'))
      } else {
        callback()
      }
    }
    const validateTel = (rule, value, callback) => {
      if (!validPhoneNumber(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }
    const validateRole = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('role不能为空'))
      } else {
        callback()
      }
    }
    const validateIdNumber = (rule, value, callback) => {
      if (!validIdNumber(value)) {
        callback(new Error('less than 6 digits or more than 16'))
      } else {
        callback()
      }
    }
    const validateMailAddress = (rule, value, callback) => {
      if (!validEmailAddress(value)) {
        callback(new Error('邮件地址不合法'))
      } else {
        callback()
      }
    }
    const validateAge = (rule, value, callback) => {
      if (value < 0 || value > 150) {
        callback(new Error('年龄不合法'))
      } else {
        callback()
      }
    }
    const validateQQ = (rule, value, callback) => {
      if (!validQQ(value)) {
        callback(new Error('qq号不正确'))
      } else {
        callback()
      }
    }
    const validateDesc = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('描述不能为空'))
      } else {
        callback()
      }
    }
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      sexs: [{ key: 0, sex: '男' },
        { key: 1, sex: '女' }],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      addUser: {
        name: 'add user',
        password: '',
        confirmedPassword: '',
        sex: '男',
        dept: '',
        role: '',
        tel: '',
        emailAddress: '',
        age: '',
        QQ: '',
        desc: '',
        idNo: ''
      },
      addRules: {
        name: [{ required: true, trigger: 'change', validator: validateUsername }],
        password: [{ required: true, trigger: 'change', validator: validatePassword }],
        confirmedPassword: [{ required: true, trigger: 'change', validator: validateConfirmedPassword }],
        birth: [{ type: 'date', required: true, message: 'birth day is required', trigger: 'change' }],
        sex: [{ required: true, trigger: 'blur', validator: validateSex }],
        dept: [{ required: true, trigger: 'change' }],
        role: [{ type: 'date', required: true, trigger: 'change', validator: validateRole }],
        tel: [{ type: 'date', required: true, trigger: 'change', validator: validateTel }],
        idNumber: [{ type: 'date', required: true, trigger: 'change', validator: validateIdNumber }],
        emailAddress: [{ type: 'date', required: true, trigger: 'change', validator: validateMailAddress }],
        age: [{ type: 'date', required: true, trigger: 'change', validator: validateAge }],
        QQ: [{ type: 'date', required: true, trigger: 'change', validator: validateQQ }],
        desc: [{ type: 'date', required: true, trigger: 'change', validator: validateDesc }]
      },
      showDetailDialog: false,
      detailUser: {},
      modifyUserDialogVisible: false,
      userRolesDialogVisible: false,
      pageRoles: {
        userPage_create: ['admin'],
        userPage_delete: ['admin'],
        userPage_retrieve: ['admin'],
        userPage_update: ['admin']
      }
    }
  },
  /* async created() {
    await this.initialRole()
  },*/
  async created() {
    this.getList()
    await this.initialRole()
  },
  methods: {
    checkPermission,
    handleDeleteUser(id) {
      deleteUserById({ 'userId': id }).then(response => {
        const h = this.$createElement
        this.$notify({
          title: '删除用户',
          message: h('i', { style: 'color: teal' }, '成功删除')
        })
      })
    },
    addUserClick() {
      addUser(this.addUser).then(response => {
        const h = this.$createElement
        this.$notify({
          title: '添加用户',
          message: h('i', { style: 'color: teal' }, '成功添加')
        })
        this.dialogFormVisible = false
      })
    },
    handleShowRoles(id) {
      this.userRolesDialogVisible = true
    },
    handleModifySubmit() {
      updateUser(this.detailUser).then(response => {
        const h = this.$createElement
        this.$notify({
          title: '修改用户',
          message: h('i', { style: 'color: teal' }, '成功修改')
        })
        this.modifyUserDialogVisible = false
      })
    },
    handleModifyUser(user) {
      this.detailUser = user
      this.modifyUserDialogVisible = true
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.items
        console.log(this.list)
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleShowDetail(user) {
      this.detailUser = user
      this.showDetailDialog = true
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    async initialRole() {
      await fetchPageRolesByPageName('userPage').then(response => {
        this.pageRoles = response.data
        console.log(this.pageRoles)
      })
    }
  }
}
</script>

<style scoped>

</style>
